package com.jjc.android.activity

import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import com.hjq.toast.ToastUtils
import com.jjc.android.Constants
import com.jjc.android.GlobalManager
import com.jjc.android.R
import com.jjc.android.base.BaseActivity
import com.jjc.android.dialog.InputTextDialog
import com.jjc.android.dialog.MessageInfoDialog
import com.jjc.android.entity.LzyResponse
import com.jjc.android.net.SimpleHttpCallback
import com.jjc.android.util.Common
import com.jjc.android.util.FileUtil
import com.jjc.android.util.OssManager
import com.jjc.android.util.OssManager.OnUploadListener
import com.jjc.android.util.paramEx
import com.jjc.android.view.MessageView
import com.jjc.android.view.onClick
import com.lxj.xpopup.XPopup
import com.lzy.okgo.OkGo
import com.otaliastudios.cameraview.PictureResult
import com.otaliastudios.cameraview.controls.PictureFormat
import com.otaliastudios.cameraview.size.AspectRatio
import java.io.File
import java.util.Date

class PicturePreviewActivity : BaseActivity() {

    companion object {
        var pictureResult: PictureResult? = null
    }


    override val layoutId: Int = R.layout.activity_picture_preview

    private val imageOutputDirectory: String by lazy { "${externalCacheDir}/images".also { File(it).mkdirs() } }
    private var uploadTime:Long = 0
    private var remoteFileUrl:String = ""
    override fun initView(savedInstanceState: Bundle?) {
        val result = pictureResult ?: run {
            finish()
            return
        }
        val uploadExceptionBtn = findViewById<View>(R.id.uploadExceptionBtn)
        val imageView = findViewById<ImageView>(R.id.image)
        val captureResolution = findViewById<MessageView>(R.id.nativeCaptureResolution)
        val captureLatency = findViewById<MessageView>(R.id.captureLatency)
        val exifRotation = findViewById<MessageView>(R.id.exifRotation)
        val pathMessage = findViewById<MessageView>(R.id.pathMessage)
        val delay = intent.getLongExtra("delay", 0)
        val tcTime = intent.getLongExtra("tcTime",0)
        val ratio = AspectRatio.of(result.size)
        captureLatency.setTitleAndMessage("Approx. latency", "$delay milliseconds")
        captureResolution.setTitleAndMessage("Resolution", "${result.size} ($ratio)")
        exifRotation.setTitleAndMessage("EXIF rotation", result.rotation.toString())

        val extension = when (requireNotNull(pictureResult).format) {
            PictureFormat.JPEG -> "jpg"
            PictureFormat.DNG -> "dng"
            else -> throw RuntimeException("Unknown format.")
        }
        val imageFile = File(imageOutputDirectory, "${System.currentTimeMillis()}.$extension")
        result.toFile(imageFile){
            pathMessage.setTitleAndMessage("File Path", it?.absolutePath?:"")
        }

        MessageInfoDialog
            .Builder(this)
            .title("温馨提示")
            .content("是否确认上传图片？")
            .btnText("取消")
            .okText("确定")
            .okClick {
                if(imageFile.exists()){
                    submitFile(extension,imageFile,tcTime)
                }else{
                    result.toFile(imageFile){file->
                        if(file!=null&&file.exists()){
                            pathMessage.setTitleAndMessage("File Path", file.absolutePath?:"")
                            submitFile(extension,file,tcTime)
                        }else{
                            ToastUtils.show("图片保存本地失败")
                        }
                    }
                }

            }
            .build()
            .show()

        uploadExceptionBtn.onClick {
            XPopup.Builder(this)
                .isDestroyOnDismiss(true)
                .asCustom(InputTextDialog(this){ code->
                    submitReport(extension,imageFile,tcTime,code)
                })
                .show()
        }
        try {
            result.toBitmap(1000, 1000) { bitmap -> imageView.setImageBitmap(bitmap) }
        } catch (e: UnsupportedOperationException) {
            imageView.setImageDrawable(ColorDrawable(Color.GREEN))
            Toast.makeText(this, "Can't preview this format: " + result.format, Toast.LENGTH_LONG).show()
        }
        if (result.isSnapshot) {
            // Log the real size for debugging reason.
            val options = BitmapFactory.Options()
            options.inJustDecodeBounds = true
            BitmapFactory.decodeByteArray(result.data, 0, result.data.size, options)
            if (result.rotation % 180 != 0) {
                Log.e("PicturePreview", "The picture full size is ${result.size.height}x${result.size.width}")
            } else {
                Log.e("PicturePreview", "The picture full size is ${result.size.width}x${result.size.height}")
            }
        }
    }

    private fun submitFile(extension:String,imageFile:File,tcTime:Long){
        val currentTime = System.currentTimeMillis()
        showLoadingDialog("上传报告中")
        OssManager.instance.upload(this,imageFile.absolutePath,object : OnUploadListener{
            override fun onSuccess(uploadPath: String, objectKey: String,imageUrl:String) {
                ToastUtils.show("上传成功：$imageUrl")
                uploadTime = System.currentTimeMillis() - currentTime
                remoteFileUrl = imageUrl
                submitReport(extension,imageFile,tcTime,null)
            }

            override fun onFailure(error: String?) {
                hideLoadingDialog()
                ToastUtils.show("上传失败：$error")
                submitReport(extension,imageFile,tcTime,null)
            }
        })
    }

    private fun submitReport(extension:String,imageFile:File,tcTime:Long,code:String?){
        val isDng = if(extension=="dng") 1 else 0
        OkGo.post<LzyResponse<String>>(Constants.reportEx)
            .paramEx(mutableMapOf(
                "phoneModel" to Build.MODEL,
                "systemVersion" to Build.VERSION.RELEASE,
                "mobileBrand" to Build.BRAND,
                "imageFormat" to extension,
                "imageFile" to remoteFileUrl,
                "fileSize" to FileUtil.getReadableFileSizeToMB(imageFile.length()),
                "tcTime" to tcTime,
                "uploadTime" to uploadTime,
                "dngState" to isDng,
                "rawState" to if(GlobalManager.isSupportRaw) 1 else 0,
                "exCondition" to code,
                "reportTime" to Common.sdf.format(Date())))
            .tag(this@PicturePreviewActivity)
            .execute(object : SimpleHttpCallback<LzyResponse<String>>(activity = this@PicturePreviewActivity){
                override fun onCallSuccess(response: LzyResponse<String>) {
                    if(code.isNullOrEmpty()){
                        hideLoadingDialog()
                        ToastUtils.show("保存地址成功：$remoteFileUrl")
                    }else{
                        ToastUtils.show("上报成功")
                    }


                }

                override fun onCallError(error: String?) {
                    super.onCallError(error)
                    if(code.isNullOrEmpty()){
                        hideLoadingDialog()
                        ToastUtils.show("上传失败：$error")
                    }
                }
            })
    }

    override fun onDestroy() {
        super.onDestroy()
        if (!isChangingConfigurations) {
            pictureResult = null
        }
    }


}